package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.quatation.pojo.dto.QuotationGetDTO;
import com.xbongbong.pro.quatation.pojo.vo.QuotationGetVO;
import com.xbongbong.saas.service.QuotationService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 *
 * @author 刘阳
 * @date 2019/8/12 3:03 PM
 * @since v1.0
 * @version v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/quotation")
public class QuotationController {
    @Resource
    private QuotationService quotationService;

    /**
     * Description: 生成新版本
     * @param quotationGetDTO
     * @param br
     * @return java.lang.String
     * @author 刘阳
     * @date 2019/8/16 10:02 PM
     * @since v1.0
     */
    @RequestMapping(value = "/newVersion/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getNewVersion(@RequestBody @Valid QuotationGetDTO quotationGetDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(quotationGetDTO.getSaasMark(), quotationGetDTO.getBusinessType(), quotationGetDTO.getMenuId(), quotationGetDTO.getDistributorMark());
                QuotationGetVO quotationGetVO = quotationService.getNewVersion(quotationGetDTO);
                response = new XbbResponse<>(quotationGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

}
